<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生端 - 课堂答题</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f9f9f9; /* 添加背景颜色 */
            color: #333; /* 调整整体文字颜色 */
        }

        .container {
            margin-bottom: 20px;
        }

        .group-select {
            display: flex;
            gap: 10px;
            margin: 10px 0;
        }

        .button {
            padding: 10px 20px; /* 增大按钮内边距 */
            background-color: #28a745; /* 调整按钮颜色 */
            color: white;
            border: none;
            border-radius: 5px; /* 调整按钮圆角 */
            cursor: pointer;
            font-size: 16px; /* 增大按钮字体大小 */
            transition: background-color 0.3s ease; /* 添加过渡效果 */
        }

        .button:hover {
            background-color: #218838; /* 按钮悬停时的颜色 */
        }

        .question-box {
            border: 1px solid #ddd;
            padding: 20px;
            margin-top: 20px;
            background-color: white; /* 题目框背景色 */
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
        }

        /* 学生姓名容器样式 */
        #studentListContainer {
            display: flex;
            flex-wrap: wrap;
            justify-content: start;
        }

        /* 单个学生姓名样式 */
        ._item_10gal_78 {
            padding: 10px 20px;
            margin: 10px;
            background-color: #e3f2fd; /* 调整学生姓名块背景色 */
            border-radius: 10px;
            cursor: pointer;
            text-align: center;
            border: 2px solid #e3f2fd;
            transition: all 0.3s ease;
            width: calc(12.5% - 20px);
            box-sizing: border-box;
        }

        ._item-active_10gal_96 {
            background-color: #28a745; /* 调整选中时学生姓名块背景色 */
            color: white;
            border-color: #28a745;
        }

        /* 欢迎信息样式 */
        #welcomeSection {
            display: none;
            margin-top: 20px;
            color: #555; /* 调整欢迎信息文字颜色 */
        }

        /* 题目区样式调整，确保与欢迎区可同时显示 */
        #questionSection {
            margin-top: 20px;
        }

        /* 学生答案区域样式 */
        .student-answer {
            margin: 10px 0;
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .student-answer span {
            font-weight: bold;
            color: #333; /* 调整学生姓名颜色 */
        }

        /* 新增选项容器样式 */
        .option-container {
            display: flex;
            gap: 15px; /* 增大选项间距 */
            font-size: 1.2em; /* 增大字体 */
            align-items: center; /* 垂直居中 */
        }

        /* 单选框样式 */
        .option-container input[type="radio"] {
            transform: scale(1.5); /* 增大单选框尺寸 */
        }

        /* 填空题输入框样式 */
        .student-answer input[type="text"] {
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 5px;
            font-size: 1em;
        }
    </style>
</head>

<body>
    <div id="loginSection">
        <h2>选择登录方式</h2>
        <div class="group-select">
            <button class="button" onclick="selectLoginType('individual')">个人登录</button>
            <button class="button" onclick="selectLoginType('group')">小组登录</button>
        </div>
    </div>

    <div id="nameSelectSection" style="display: none;">
        <h3>选择姓名</h3>
        <div id="studentListContainer"></div>
        <button class="button" onclick="confirmNames()">确认登录</button>
    </div>

    <div id="welcomeSection">
        <h3 id="welcomeMessage"></h3>
    </div>

    <div id="questionSection" style="display: none;">
        <div class="question-box" id="currentQuestion"></div>
        <div id="optionsContainer"></div>
        <button class="button" id="submitBtn" onclick="submitAnswer()" style="display: none;">提交答案</button>
    </div>

    <script src="/socket.io/socket.io.js"></script>
    <script>
        const socket = io('/student');
        let currentUser = { type: '', names: [] };
        let currentQuestion = null;

        // 登录方式选择
        function selectLoginType(type) {
            currentUser.type = type;
            document.getElementById('loginSection').style.display = 'none';
            document.getElementById('nameSelectSection').style.display = 'block';
            fetch('/api/students')
              .then(res => {
                    if (!res.ok) throw new Error(`网络响应异常：${res.status}`);
                    return res.json();
                })
              .then(students => {
                    // 原错误逻辑：students被当作对象数组处理（s.student_names）
                    // 修正后：students本身就是姓名的字符串数组（如["张三", "李四"]）
                    const names = [...new Set(students)]; // 直接使用接口返回的数组去重（实际接口已去重，可简化为const names = students）
                    const container = document.getElementById('studentListContainer');
                    container.innerHTML = ''; // 清空容器
                    names.forEach(name => {
                        const div = document.createElement('div');
                        div.className = '_item_10gal_78'; // 初始类
                        div.textContent = name;
                        div.onclick = function () {
                            if (currentUser.type === 'individual') {
                                // 个人登录时，取消其他已选姓名的选中状态
                                const selectedDivs = document.querySelectorAll('#studentListContainer div._item-active_10gal_96');
                                selectedDivs.forEach(selectedDiv => {
                                    if (selectedDiv!== this) {
                                        selectedDiv.classList.remove('_item-active_10gal_96');
                                    }
                                });
                            }
                            // 切换选中状态
                            if (this.classList.contains('_item-active_10gal_96')) {
                                this.classList.remove('_item-active_10gal_96');
                            } else {
                                this.classList.add('_item-active_10gal_96');
                            }
                        };
                        container.appendChild(div);
                    });
                })
              .catch(error => {
                    console.error('获取学生列表失败:', error);
                    alert('无法加载学生列表，请稍后重试');
                });
        }

        // 确认姓名
        // 在页面加载时检查登录状态
        window.addEventListener('DOMContentLoaded', () => {
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                currentUser = JSON.parse(savedUser);
                document.getElementById('loginSection').style.display = 'none';
                document.getElementById('nameSelectSection').style.display = 'none';
                document.getElementById('welcomeSection').style.display = 'block';
                document.getElementById('welcomeMessage').textContent = `欢迎回来：${currentUser.names.join(', ')}`;
                
                // 重新连接socket并恢复状态
                socket.emit('restoreSession', currentUser);
            }
        });
        
        // 修改confirmNames函数，保存用户信息
        function confirmNames() {
            const selectedDivs = document.querySelectorAll('#studentListContainer div._item-active_10gal_96');
            currentUser.names = Array.from(selectedDivs).map(div => div.textContent);
            
            if (!Array.isArray(currentUser.names) || currentUser.names.length === 0) {
                alert('请选择至少一个有效学生姓名');
                return;
            }
            
            // 保存用户信息到localStorage
            localStorage.setItem('currentUser', JSON.stringify(currentUser));
            
            const loginData = {
                loginType: currentUser.type,
                studentNames: currentUser.names
            };
            
            socket.emit('login', loginData);
            if (currentUser.type === 'individual' && currentUser.names.length === 0) {
                alert('个人登录请选择一个姓名');
                return;
            } else if (currentUser.type === 'group' && currentUser.names.length === 0) {
                alert('小组登录请选择至少一个姓名');
                return;
            }
            document.getElementById('nameSelectSection').style.display = 'none';
            document.getElementById('welcomeSection').style.display = 'block';
            let welcomeText = `欢迎你：${currentUser.names.join(', ')}`;
            document.getElementById('welcomeMessage').textContent = welcomeText;
            socket.emit('studentLogin', currentUser);
        }

        // 监听题目发布
        socket.on('questionPublished', (question) => {
            currentQuestion = question;
            if (currentUser.names.length > 0) {
                document.getElementById('welcomeSection').style.display = 'none';
                document.getElementById('questionSection').style.display = 'block';
                // 重置选项容器的display样式
                document.getElementById('optionsContainer').style.display = 'block'; 
                renderQuestion(question);
            }
        });

        // 渲染题目
        function renderQuestion(question) {
            const questionDiv = document.getElementById('currentQuestion');
            questionDiv.innerHTML = `<h3>${question.question}</h3>`;
            const optionsDiv = document.getElementById('optionsContainer');
            optionsDiv.innerHTML = '';

            if (question.type === 'choice') {
                if (currentUser.type === 'individual') {
                    const studentName = currentUser.names[0];
                    const optionContainer = document.createElement('div');
                    optionContainer.className = 'option-container';
                    question.options.forEach(option => {
                        const optionElement = document.createElement('div');
                        const radioInput = document.createElement('input');
                        radioInput.type = 'radio';
                        radioInput.name = `answer_${studentName}`;
                        radioInput.value = option;
                        const label = document.createElement('label');
                        label.textContent = option;
                        optionElement.appendChild(radioInput);
                        optionElement.appendChild(label);
                        optionContainer.appendChild(optionElement);
                    });
                    optionsDiv.innerHTML += `<div class="student-answer">
                        <span>${studentName}</span>
                        ${optionContainer.outerHTML}
                    </div>`;
                } else if (currentUser.type === 'group') {
                    currentUser.names.forEach(studentName => {
                        const optionContainer = document.createElement('div');
                        optionContainer.className = 'option-container';
                        question.options.forEach(option => {
                            const optionElement = document.createElement('div');
                            const radioInput = document.createElement('input');
                            radioInput.type = 'radio';
                            radioInput.name = `answer_${studentName}`;
                            radioInput.value = option;
                            const label = document.createElement('label');
                            label.textContent = option;
                            optionElement.appendChild(radioInput);
                            optionElement.appendChild(label);
                            optionContainer.appendChild(optionElement);
                        });
                        optionsDiv.innerHTML += `<div class="student-answer">
                            <span>${studentName}</span>
                            ${optionContainer.outerHTML}
                        </div>`;
                    });
                }
            } else if (question.type === 'fill') {
                if (currentUser.type === 'individual') {
                    const studentName = currentUser.names[0];
                    optionsDiv.innerHTML += `<div class="student-answer">
                        <span>${studentName}</span>
                        <input type="text" id="answer_${studentName}" name="answer_${studentName}" placeholder="请输入答案">
                    </div>`;
                } else if (currentUser.type === 'group') {
                    currentUser.names.forEach(studentName => {
                        optionsDiv.innerHTML += `<div class="student-answer">
                            <span>${studentName}</span>
                            <input type="text" id="answer_${studentName}" name="answer_${studentName}" placeholder="请输入答案">
                        </div>`;
                    });
                }
            }
            document.getElementById('submitBtn').style.display = 'block';
            document.getElementById('submitBtn').disabled = false;
        }

        // 提交答案
        function submitAnswer() {
            const answers = {};
            if (currentQuestion.type === 'choice') {
                // 选择题答案获取逻辑不变
                if (currentUser.type === 'individual') {
                    const selected = document.querySelector(`input[name="answer_${currentUser.names[0]}"]:checked`);
                    if (!selected) return alert('请选择答案');
                    answers[currentUser.names[0]] = selected.value;
                } else if (currentUser.type === 'group') {
                    currentUser.names.forEach(studentName => {
                        const selected = document.querySelector(`input[name="answer_${studentName}"]:checked`);
                        if (!selected) {
                            alert(`请选择${studentName}的答案`);
                            return;
                        }
                        answers[studentName] = selected.value;
                    });
                }
            } else if (currentQuestion.type === 'fill') {
                // 修改填空题答案获取逻辑
                if (currentUser.type === 'individual') {
                    const input = document.getElementById(`answer_${currentUser.names[0]}`);
                    const answer = input.value;
                    if (!answer) return alert('请输入答案'); // 正确提示输入答案
                    answers[currentUser.names[0]] = answer;
                } else if (currentUser.type === 'group') {
                    currentUser.names.forEach(studentName => {
                        const input = document.getElementById(`answer_${studentName}`);
                        const answer = input.value;
                        if (!answer) {
                            alert(`请${studentName}输入答案`);
                            return;
                        }
                        answers[studentName] = answer;
                    });
                }
            }
            // 后续提交逻辑
            socket.emit('submitAnswer', { 
                questionId: currentQuestion.id, 
                answers: answers, 
                user: currentUser 
            });
            document.getElementById('submitBtn').disabled = true;
            document.getElementById('optionsContainer').style.display = 'none';
            alert('答案提交成功！等待老师发布下一题');
        }
        socket.on('connect', () => {
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                socket.emit('restoreSession', JSON.parse(savedUser));
            }
        });
        // 添加接收工具链接的代码
        socket.on('receiveToolLink', (data) => {
            console.log('收到工具链接:', data); // 调试日志
            const toolLinkSection = document.getElementById('toolLinkSection');
            if(!toolLinkSection) {
                // 动态创建按钮区域
                const section = document.createElement('div');
                section.id = 'toolLinkSection';
                section.innerHTML = `
                    <button class="button" id="toolLinkBtn" style="background-color:#4CAF50;margin-top:20px;">
                        打开计算工具
                    </button>
                `;
                document.body.appendChild(section);
            }
            document.getElementById('toolLinkBtn').onclick = () => window.open(data.url);
        });
    </script>
</body>

</html>
